package com.explorex.infra.puma.gateway.netty.common.utils;

import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;

/**
 * Created by wuhaodong on 2018/12/10.
 */
public class ProtobufJsonMapper {

    private static final JsonFormat.Printer jsonPrinter = JsonFormat.printer().omittingInsignificantWhitespace();
    private static final JsonFormat.Parser jsonParser = JsonFormat.parser().ignoringUnknownFields();

    public static <T extends Message> T loadObject(String jsonStr, Class<T> clazz) {
        if (StringUtils.isBlank(jsonStr)) {
            return null;
        }
        try {
            Method newBuilder = clazz.getDeclaredMethod("newBuilder");
            Message.Builder builder = (Message.Builder) newBuilder.invoke(clazz);
            jsonParser.merge(jsonStr, builder);
            return (T) builder.build();
        } catch (Exception e) {
            return null;
        }
    }

    public static String dumpObject(Message object) {
        if (object == null) {
            return null;
        }
        try {
            return jsonPrinter.print(object);
        } catch (Exception e) {
            return null;
        }
    }
}
